/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Search.java
 *
 * Created on Dec 20, 2008, 4:54:52 PM
 */
package GUI;

import Dictionary.Dictionary;
import GUI.other.fastDogAdd;
import VoiceIdent.SPitch;
import java.awt.event.ActionEvent;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.Item;
import functions.*;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.util.Collections;
import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.DefaultMutableTreeNode;

import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import model.Diagnose;
import model.Dog;
import model.Drug;
import functions.OldUsers;
import java.awt.Color;
import java.awt.Component;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import javax.swing.SwingWorker;
import javax.swing.table.TableCellRenderer;
import javax.swing.tree.TreeModel;
import model.Operation;
import model.User;
import model.Visit;
import stuff.FormException;

/**
 *
 * @author GiK
 */
public class UserCard extends javax.swing.JFrame {
    // @Exception handler

    private VisitInfo vInfo;
    private FinInfo fInfo;
    private MainFrame frame;
    private ArrayList<HealingSet> healings;
    private ItemList activeVisit=null;
    private User user;
    private OldVisits oldVisits;
    private int visitToSelect=0;
    private String visitHeaderCaption = "<html>Визиты(<b>F2</b>):";
    //private Dog dog;
    /** Creates new form Search */
    public UserCard(final MainFrame mainFr, final User nUser) {
        initComponents();
        this.setTitle("Карта: " + nUser.getFullName() + " Загрузка... ");
        visitTree.setRowHeight(0);
        final UserCard currWindow = this;
        jPanel1.setVisible(true);
        jPanel1.repaint();
        visitDescr.repaint();

        if(SPitch.isStarted())
            SPitch.setActiveUser(nUser);
        
        SwingWorker fill = new SwingWorker()
        {
            private ArrayList<Dog> dogs=null;
            @Override
            protected Object doInBackground() throws Exception
            {
                user = nUser;
                frame = mainFr;
                Dog dog = null;

                //this.getContentPane().add(inWindow);

                //if (nUser.getDog() != null || nUser.getDogId() != 0)
                //{
                    dog = nUser.getDog();
                    try {
                        dogs = nUser.getDogs();
                        
                        if(dogsTable.getModel().getRowCount() == 0)
                            emptyPriem();
                        else
                        {
                          visitTree.setSelectionRow(0);
                          visitTree.expandRow(0);
                        }
                    } catch (SQLException ex) {
                        ex.printStackTrace();
                        frame.SQLException(ex);
                    }
                //}else



                usersNameLabel.setText(user.getFullName());

                usersAddressLabel.setText(user.getFullAddress() +
                        (!user.getTel().equals("") ? "\nТелефон:" + user.getTel() : "") +
                        (!user.getEmail().equals("") ? "\nE-mail:" + user.getEmail() : ""));

                
                //showDetails.setSelected(true);

                
                
                currWindow.setTitle("Карта: " + nUser.getFullName());


                if(healings == null || healings.size() == 0)
                   ;//emptyPriem();
                else
                  visitTreeValueChanged(null);
                
                return null;
            }
            
            @Override
            protected void done()
            {
                //pack();
                if(dogs != null)
                  fillDogTable(dogs);
                
                
                dogsTable.requestFocus();
            }

        };
        pack();
        Dogy.placeToCenter(currWindow);
        Dogy.reSize(currWindow);
        
        KeyStroke kStroke = KeyStroke.getKeyStroke(KeyEvent.VK_W,2);
        InputMap map = visitTree.getInputMap(javax.swing.JTable.WHEN_IN_FOCUSED_WINDOW);
        map.put(kStroke, "ctrlW");
        ActionMap actionMap = visitTree.getActionMap();
        actionMap.put("ctrlW", new AbstractAction() {
                     public void actionPerformed(ActionEvent actionEvent)
                     {
                        ((javax.swing.JFrame)visitTree.getRootPane().getParent()).dispose();
                     }
             });

        kStroke = KeyStroke.getKeyStroke(KeyEvent.VK_F5,0);
        map = visitTree.getInputMap(javax.swing.JTable.WHEN_IN_FOCUSED_WINDOW);
        map.put(kStroke, "newVisit");
        actionMap = visitTree.getActionMap();
        actionMap.put("newVisit", new AbstractAction() {
                     public void actionPerformed(ActionEvent actionEvent)
                     {
                        newVisit();
                     }
             });
        kStroke = KeyStroke.getKeyStroke(KeyEvent.VK_F6,0);
        map = dogsTable.getInputMap(javax.swing.JTable.WHEN_IN_FOCUSED_WINDOW);
        map.put(kStroke, "newKurs");
        dogsTable.getInputMap(javax.swing.JTable.WHEN_FOCUSED).put(kStroke, "newKurs");
        actionMap = dogsTable.getActionMap();
        actionMap.put("newKurs", new AbstractAction() {
                     public void actionPerformed(ActionEvent actionEvent)
                     {
                        newHealingActionPerformed(null);
                     }
             });

        kStroke = KeyStroke.getKeyStroke(KeyEvent.VK_F2,0);
        map = visitTree.getInputMap(javax.swing.JTable.WHEN_IN_FOCUSED_WINDOW);
        map.put(kStroke, "visitFocus");
        actionMap = visitTree.getActionMap();
        actionMap.put("visitFocus", new AbstractAction() {
                     public void actionPerformed(ActionEvent actionEvent)
                     {
                        visitTree.requestFocus();
                     }
             });

        kStroke = KeyStroke.getKeyStroke(KeyEvent.VK_F1,0);
        map = visitTree.getInputMap(javax.swing.JTable.WHEN_IN_FOCUSED_WINDOW);
        map.put(kStroke, "dogFocus");
        actionMap = visitTree.getActionMap();
        actionMap.put("dogFocus", new AbstractAction() {
                     public void actionPerformed(ActionEvent actionEvent)
                     {
                        dogsTable.requestFocus();
                     }
             });

        kStroke = KeyStroke.getKeyStroke(KeyEvent.VK_F9,0);
        map = visitTree.getInputMap(javax.swing.JTable.WHEN_IN_FOCUSED_WINDOW);
        map.put(kStroke, "oldVisits");
        actionMap = visitTree.getActionMap();
        actionMap.put("oldVisits", new AbstractAction() {
                     public void actionPerformed(ActionEvent actionEvent)
                     {
                         if(!showDetails.isSelected())
                           showDetails.setSelected(true);
                         else
                           showDetails.setSelected(false);
                         showDetailsActionPerformed(null);
                     }
             });
      //java.awt.EventQueue.invokeLater(fill);
      fill.execute();
    }
    public void newVisit()
    {
        try
        {
            if(visitTree.getRowCount() > 0)
                newVisitButtonActionPerformed(null);
            else
                newHealingActionPerformed(null);
        }catch(Exception e)
        {
            frame.FormException(this,e.getMessage());
        }
    }
    public void emptyPriem()
    {
        visitDescr.removeAll();
        visitsHeader.setText(visitHeaderCaption);
        GridLayout grid = new GridLayout(0,1);
        JPanel panel = new JPanel(grid);

        JLabel label = new JLabel("<html><center><font color=grey>Выделите животное, визиты которого вы хотите посмотреть.</font></center>");
        label.setSize(panel.getWidth(), panel.getHeight());
        panel.add(label);
        visitDescr.add("Прием", panel);
    }
    public void showNoVisits()
    {
        visitDescr.removeAll();
        visitsHeader.setText(visitHeaderCaption);
        GridLayout grid = new GridLayout(0,1);
        JPanel panel = new JPanel(grid);

        JLabel label = new JLabel("<html><center><font color=grey>У этого животного нет ни одного визита.</font></center>");
        label.setSize(panel.getWidth(), panel.getHeight());
        panel.add(label);
        visitDescr.add("Прием", panel);
    }
    public void showPriemLoading()
    {
        visitDescr.removeAll();
        GridLayout grid = new GridLayout(1,1);
        JPanel panel = new JPanel(grid);

        JLabel label = new JLabel("<html><center><font color=grey><b>Пожалуйста подождите, идет обработка визитов.</b></font></center>");
        label.setSize(panel.getWidth(), panel.getHeight());
        panel.add(label);
        visitDescr.add("Загрузка", panel);
    }

    public void fillDogTable(ArrayList<Dog> dogs) {
        DefaultTableModel model = (DefaultTableModel) dogsTable.getModel();
        model.setRowCount(0);
        if(dogs.size() <= 0 )
            return;
        int selId = 0;
        for (int i = 0; i < dogs.size(); i++) {
            model.addRow(new Object[]{dogs.get(i)});
            if (user.getDog() != null && user.getDog().getId() == dogs.get(i).getId()) {
                selId = i;
            }
        }
        //dogsTable.requestFocusInWindow();
        dogsTable.setModel(model);
        dogsTable.setRowSelectionInterval(selId, selId);
        Rectangle r = dogsTable.getCellRect(selId, 0, true);
        dogsTable.scrollRectToVisible(r);
        dogsTableMousePressed(null);
    }
    public void fillDogTable(ArrayList<Dog> dogs, int dogId) {
        DefaultTableModel model = (DefaultTableModel) dogsTable.getModel();
        model.setRowCount(0);
        if(dogs.size() <= 0 )
            return;
        int selId = 0;
        for (int i = 0; i < dogs.size(); i++) {
            model.addRow(new Object[]{dogs.get(i)});
            if (dogId == dogs.get(i).getId()) {
                selId = i;
            }
        }
        
        dogsTable.setModel(model);
        dogsTable.setRowSelectionInterval(selId, selId);
        Rectangle r = dogsTable.getCellRect(selId, 0, true);
        dogsTable.scrollRectToVisible(r);
        //dogsTableMousePressed(null);
    }
    private void initVisitTree() {
        DefaultMutableTreeNode visit = null, healing = null;
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("Визиты");
        HealingSet heal;
        if (healings != null && healings.size() > 0) {
            DefaultMutableTreeNode toSelect=null;
            for (int i = 0; i < healings.size(); i++) // get healing
            {
                healing = new DefaultMutableTreeNode(healings.get(i));
                heal = healings.get(i);
                for (int x = 0; x < heal.size(); x++) // get visit
                {
                    visit = new DefaultMutableTreeNode(heal.getVisit(x));
                    healing.add(visit);
                    for (int y = 0; y < heal.getVisit(x).size(); y++) // get visit items
                    {
                        if (heal.getVisit(x).get(y) instanceof Drug) {
                            visit.add(new DefaultMutableTreeNode("Выдано: " + heal.getVisit(x).get(y)));
                        }
                        if (heal.getVisit(x).get(y) instanceof Operation) {
                            visit.add(new DefaultMutableTreeNode("Сделано: " + heal.getVisit(x).get(y)));
                        }
                        if (heal.getVisit(x).get(y) instanceof Diagnose) {
                            visit.add(new DefaultMutableTreeNode("Диагноз: " + heal.getVisit(x).get(y)));
                        }
                        if (heal.getVisit(x).get(y) instanceof Visit) {
                            if (heal.getVisit(x).get(y).toString() != null) {

                                visit.add(new DefaultMutableTreeNode("Описание: " + heal.getVisit(x).get(y)));
                                visit.add(new DefaultMutableTreeNode(
                                        "Рекомендации : " + ((Visit)heal.getVisit(x).get(y)).getRecom()));
                                if(((Visit)heal.getVisit(x).get(y)).getId() == visitToSelect)
                                    toSelect = visit;
                            }
                        }

                    }
                }
                root.add(healing);
            }
            visitTree.setModel(new javax.swing.tree.DefaultTreeModel(root));
            if(toSelect != null)
            {
              visitTree.expandRow(root.getIndex(toSelect.getParent()));
              visitTree.setSelectionRow(root.getIndex(toSelect.getParent()) +
                                       toSelect.getParent().getIndex(toSelect)+1);
              visitToSelect = 0;
            }
        }

    }

    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane3 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        usersNameLabel = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        visitTree = new javax.swing.JTree();
        newVisitButton = new javax.swing.JButton();
        visitsHeader = new javax.swing.JLabel();
        closeButton = new javax.swing.JButton();
        selectAll = new javax.swing.JButton();
        jPanel1 = new javax.swing.JPanel();
        visitDescr = new javax.swing.JTabbedPane();
        jPanel2 = new javax.swing.JPanel();
        loadingLabel = new javax.swing.JLabel();
        showDetails = new javax.swing.JToggleButton();
        jSplitPane1 = new javax.swing.JSplitPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        usersAddressLabel = new javax.swing.JTextPane();
        jScrollPane4 = new javax.swing.JScrollPane();
        dogsTable = new javax.swing.JTable(){
            public String getToolTipText(MouseEvent e)
            {
                String tip = null;
                java.awt.Point p = e.getPoint();
                int rowIndex = dogsTable.rowAtPoint(p);
                return getValueAt(rowIndex,0).toString();
            }
            public Component prepareRenderer(TableCellRenderer renderer,
                int rowIndex, int vColIndex) {
                Component c = super.prepareRenderer(renderer, rowIndex, vColIndex);
                if(this.getValueAt(rowIndex, 0) instanceof Dog)
                if (((Dog)this.getValueAt(rowIndex, 0)).isDead() &&
                    !isCellSelected(rowIndex, vColIndex)) {
                    c.setBackground(Color.lightGray);
                }else
                if(!isCellSelected(rowIndex, vColIndex))
                c.setBackground(Color.white);
                return c;
            }
        };
        newHealing = new javax.swing.JButton();
        changeVisit = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane3.setViewportView(jTable1);

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });
        addHierarchyBoundsListener(new java.awt.event.HierarchyBoundsListener() {
            public void ancestorMoved(java.awt.event.HierarchyEvent evt) {
            }
            public void ancestorResized(java.awt.event.HierarchyEvent evt) {
                formAncestorResized(evt);
            }
        });

        usersNameLabel.setFont(new java.awt.Font("Tahoma", 0, 14));
        usersNameLabel.setText("Name Surname");
        usersNameLabel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(179, 179, 179)));

        visitTree.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        javax.swing.tree.DefaultMutableTreeNode treeNode1 = new javax.swing.tree.DefaultMutableTreeNode("root");
        visitTree.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        visitTree.setToolTipText("");
        visitTree.setRootVisible(false);
        visitTree.setRowHeight(23);
        visitTree.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                visitTreeMouseReleased(evt);
            }
        });
        visitTree.addTreeExpansionListener(new javax.swing.event.TreeExpansionListener() {
            public void treeCollapsed(javax.swing.event.TreeExpansionEvent evt) {
            }
            public void treeExpanded(javax.swing.event.TreeExpansionEvent evt) {
                visitTreeTreeExpanded(evt);
            }
        });
        visitTree.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                visitTreeValueChanged(evt);
            }
        });
        visitTree.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                visitTreeKeyReleased(evt);
            }
        });
        jScrollPane2.setViewportView(visitTree);

        newVisitButton.setFont(new java.awt.Font("Tahoma", 1, 13));
        newVisitButton.setText(Dictionary.NEW_VISIT+"(F5)");
        newVisitButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newVisitButtonActionPerformed(evt);
            }
        });

        visitsHeader.setFont(new java.awt.Font("Tahoma", 0, 14));
        visitsHeader.setText("<html>"+Dictionary.VISITS+"(<b>F2</b>):");
        visitsHeader.setToolTipText("Удерживайте <control> для выделения отдельных визитов.");
        visitsHeader.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(179, 179, 179)));

        closeButton.setFont(new java.awt.Font("Tahoma", 1, 13));
        closeButton.setText(Dictionary.CLOSE);
        closeButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                closeButtonActionPerformed(evt);
            }
        });

        selectAll.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        selectAll.setText(Dictionary.CLOSE_ALL);
        selectAll.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                selectAllActionPerformed(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel1.addHierarchyBoundsListener(new java.awt.event.HierarchyBoundsListener() {
            public void ancestorMoved(java.awt.event.HierarchyEvent evt) {
            }
            public void ancestorResized(java.awt.event.HierarchyEvent evt) {
                jPanel1AncestorResized(evt);
            }
        });

        visitDescr.setTabLayoutPolicy(javax.swing.JTabbedPane.SCROLL_TAB_LAYOUT);
        visitDescr.setFont(new java.awt.Font("Tahoma", 1, 14));
        visitDescr.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                visitDescrStateChanged(evt);
            }
        });
        visitDescr.addHierarchyBoundsListener(new java.awt.event.HierarchyBoundsListener() {
            public void ancestorMoved(java.awt.event.HierarchyEvent evt) {
            }
            public void ancestorResized(java.awt.event.HierarchyEvent evt) {
                visitDescrAncestorResized(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 695, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 269, Short.MAX_VALUE)
        );

        visitDescr.addTab("Нет животных", jPanel2);

        loadingLabel.setFont(new java.awt.Font("Tahoma", 1, 18));
        loadingLabel.setText("Загрузка...");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(visitDescr)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(250, 250, 250)
                .addComponent(loadingLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 290, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(visitDescr, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(100, 100, 100)
                .addComponent(loadingLabel))
        );

        showDetails.setFont(new java.awt.Font("Tahoma", 1, 12));
        showDetails.setText(Dictionary.SHOW_OLD_VISITS+"(F9)");
        showDetails.setMaximumSize(new java.awt.Dimension(99, 50));
        showDetails.setMinimumSize(new java.awt.Dimension(99, 50));
        showDetails.setPreferredSize(new java.awt.Dimension(99, 50));
        showDetails.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                showDetailsActionPerformed(evt);
            }
        });

        jSplitPane1.setBorder(null);
        jSplitPane1.setDividerLocation(60);
        jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        jSplitPane1.setContinuousLayout(true);

        jScrollPane1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, Dictionary.CONTACT_DATA, javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(0, 0, 0)));

        usersAddressLabel.setBackground(new java.awt.Color(236, 233, 216));
        usersAddressLabel.setBorder(null);
        usersAddressLabel.setEditable(false);
        usersAddressLabel.setFont(new java.awt.Font("Tahoma", 0, 12));
        usersAddressLabel.setFocusCycleRoot(false);
        usersAddressLabel.setOpaque(false);
        jScrollPane1.setViewportView(usersAddressLabel);

        jSplitPane1.setTopComponent(jScrollPane1);

        dogsTable.setAutoCreateRowSorter(true);
        dogsTable.setFont(new java.awt.Font("Tahoma", 1, 13)); // NOI18N
        dogsTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"Нет животных"}
            },
            new String [] {
                "<html>Животные(<b>F1</b>)"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }

        });
        dogsTable.setRowHeight(23);
        dogsTable.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        dogsTable.setShowVerticalLines(false);
        dogsTable.getTableHeader().setResizingAllowed(false);
        dogsTable.getTableHeader().setReorderingAllowed(false);
        dogsTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                onClick(evt);
            }
            public void mousePressed(java.awt.event.MouseEvent evt) {
                dogsTableMousePressed(evt);
            }
        });
        dogsTable.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                dogsTableKeyReleased(evt);
            }
        });
        jScrollPane4.setViewportView(dogsTable);
        dogsTable.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        dogsTable.getColumnModel().getColumn(0).setResizable(false);

        jSplitPane1.setRightComponent(jScrollPane4);

        newHealing.setFont(new java.awt.Font("Tahoma", 1, 13));
        newHealing.setText(Dictionary.NEW_COURSE+"(F6)");
        newHealing.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newHealingActionPerformed(evt);
            }
        });

        changeVisit.setFont(new java.awt.Font("Tahoma", 1, 13));
        changeVisit.setText(Dictionary.CHANGE_COURSE_VISIT);
        changeVisit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                changeVisitActionPerformed(evt);
            }
        });

        jButton2.setFont(new java.awt.Font("Tahoma", 1, 11));
        jButton2.setText(Dictionary.ADD_CHANGE_PETS);
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
                            .addComponent(usersNameLabel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE)
                            .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 300, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 398, Short.MAX_VALUE)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(selectAll)
                                .addGap(10, 10, 10)
                                .addComponent(showDetails, javax.swing.GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE))
                            .addComponent(visitsHeader, javax.swing.GroupLayout.DEFAULT_SIZE, 398, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(closeButton)
                        .addGap(59, 59, 59)
                        .addComponent(changeVisit, javax.swing.GroupLayout.DEFAULT_SIZE, 200, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(newHealing, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(newVisitButton, javax.swing.GroupLayout.PREFERRED_SIZE, 177, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(visitsHeader)
                    .addComponent(usersNameLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(selectAll, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(showDetails, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(7, 7, 7)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(closeButton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(newVisitButton, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(newHealing, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(changeVisit, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:                                        
    }//GEN-FIRST:event_selectAllActionPerformed
    
    private void selectAllActionPerformed(java.awt.event.ActionEvent evt) {//GEN-HEADEREND:event_selectAllActionPerformed
        visitDescr.removeAll();
        for (int i = 0; i < visitTree.getRowCount(); i++) {
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) visitTree.getPathForRow(i).getLastPathComponent();
            if (node != null && node.getUserObject() != null)
                if (node.getUserObject() instanceof HealingSet)
                    visitTree.collapseRow(i);
        }
        visitTreeValueChanged(null);
}//GEN-LAST:event_selectAllActionPerformed
        
    
    private void onClick(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_onClick
    }//GEN-LAST:event_onClick

    private void dogsTableMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_dogsTableMousePressed
        DefaultTreeModel model = (DefaultTreeModel) visitTree.getModel();
        model.setRoot(null);
        showPriemLoading();
        Thread fill = new Thread()
        {
            public void run()
            {
                if (dogsTable.getSelectedRow() != -1 &&
                        dogsTable.getValueAt(dogsTable.getSelectedRow(), 0) instanceof Dog)
                {
                    showNoVisits();
                    Dog dog = (Dog) dogsTable.getValueAt(dogsTable.getSelectedRow(), 0);
                    try {
                        //System.out.println("healing");
                        healings = dog.getHealing();
                        initVisitTree();
                        visitsHeader.setText(visitHeaderCaption + " <b>"+dog+"</b>");

                        //openAllButtonActionPerformed(null);
                        //visitTreeMousePressed(null);
                        if(visitTree.getRowCount() > 0)
                        {
                            if(visitTree.getSelectionCount() == 0)
                            {
                              visitTree.setSelectionRow(0);
                              visitTree.expandRow(0);
                            }
                            visitTreeValueChanged(null);
                        }
                    } catch (SQLException ex) {
                        frame.SQLException(ex);
                    }
                } else
                {
                    emptyPriem();
                }
          }
        };
        java.awt.EventQueue.invokeLater(fill);
    }//GEN-LAST:event_dogsTableMousePressed

    private void visitTreeValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_visitTreeValueChanged
        if (showDetails.isSelected() && !jPanel1.isVisible()) {
            jPanel1.setVisible(true);
            pack();
        }
        if(evt != null) return;
        if (evt == null) {
            if(visitTree.getSelectionPath() == null)
                return;
            if (visitTree.getSelectionPath().getLastPathComponent() instanceof Item) {
                return;
            }
        }
        if(evt != null && !evt.isAddedPath()) return;
        
        ArrayList<Integer> toSel = new ArrayList<Integer>();
        int selRows[] = visitTree.getSelectionRows();
        int r;
        DefaultMutableTreeNode node;
        if (selRows != null && selRows.length != 0) {
            for (int y = 0; y < selRows.length; y++) {
                node = (DefaultMutableTreeNode) visitTree.getPathForRow(selRows[y]).getLastPathComponent();

                if (node.getUserObject() instanceof ItemList) {
                    if(!toSel.contains(selRows[y]))
                      toSel.add(selRows[y]);
                } else if (node.getUserObject() instanceof Item) {
                    r = visitTree.getRowForPath(visitTree.getPathForRow(selRows[y]).getParentPath());
                    if(!toSel.contains(r))
                      toSel.add(r);
                } else if (node.getUserObject() instanceof HealingSet) {

                    toSel.add(selRows[y]);
                    for (int i = node.getChildCount() - 1; i >= 0; i--) {
                        DefaultMutableTreeNode child = (DefaultMutableTreeNode) node.getChildAt(i);
                        TreeNode[] path = child.getPath();
                        r = visitTree.getRowForPath(new TreePath(path));
                        if (r != -1) {
                            if (!toSel.contains(r)) {
                                toSel.add(r);
                            }
                        }
                    }

                }

            }
        } else {
        }

        Collections.sort(toSel);
        ArrayList<ItemList<Item>> vis = new ArrayList<ItemList<Item>>();

        for (int i = 0; i < toSel.size(); i++) {
            node = (DefaultMutableTreeNode) visitTree.getPathForRow(toSel.get(i)).getLastPathComponent();
            if (node.getUserObject() instanceof ItemList) {
                vis.add((ItemList) node.getUserObject());
            }
        }
        if (vInfo != null) {
            vInfo.dispose();
        }
        //System.out.println("cr");
        vInfo = new VisitInfo(frame, vis, this);
        fInfo = new FinInfo(frame,vis,this);
        int selTab=0;
        if(visitDescr.getSelectedIndex() != -1)
        selTab = visitDescr.getSelectedIndex();

        visitDescr.removeAll();

        if(visitDescr.getTabCount() > 0 )
            visitDescr.removeTabAt(0);
        visitDescr.add(Dictionary.DETAILS, vInfo.getContentPane());
        visitDescr.add(Dictionary.FIN_REPORT, fInfo.getContentPane());
        visitDescr.setSelectedIndex(selTab);

    }//GEN-LAST:event_visitTreeValueChanged

    private void jPanel1AncestorResized(java.awt.event.HierarchyEvent evt) {//GEN-FIRST:event_jPanel1AncestorResized
        //visitDescr.setSize(jPanel1.getSize());
        //visitDescr.setPreferredSize(jPanel1.getSize());
        //visitDescr.setMinimumSize(jPanel1.getSize());
        //inWindow.setBounds(visitDescr.getWidth() - inWindow.getWidth(), 0, 99, 23);
        //pack();

    }//GEN-LAST:event_jPanel1AncestorResized

    private void formAncestorResized(java.awt.event.HierarchyEvent evt) {//GEN-FIRST:event_formAncestorResized
        // TODO add your handling code here:
    }//GEN-LAST:event_formAncestorResized

    private void visitDescrAncestorResized(java.awt.event.HierarchyEvent evt) {//GEN-FIRST:event_visitDescrAncestorResized
        // TODO add your handling code here:
    }//GEN-LAST:event_visitDescrAncestorResized

    private void showDetailsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_showDetailsActionPerformed
        if (!showDetails.isSelected())
        {
            if(oldVisits == null)
                return;
            oldVisits.dispose();
            //Dogy.placeToCenter(this);
        } else {
            oldVisits = new OldVisits(frame, user, this);
            oldVisits.pack();
            Dogy.placeToCenter(oldVisits);
            //this.setLocation(this.getLocation().x - oldVisits.getWidth()/2, this.getLocation().y);
            //oldVisits.setLocation(this.getLocation().x+this.getWidth(), this.getLocation().y);
            oldVisits.setVisible(true);
        }
        
}//GEN-LAST:event_showDetailsActionPerformed

    public void setOldVisitsVisible(boolean vis)
    {
        showDetails.setSelected(vis);
    }
    private void visitTreeKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_visitTreeKeyReleased

        visitTreeValueChanged(null);
    }//GEN-LAST:event_visitTreeKeyReleased

    private void visitTreeTreeExpanded(javax.swing.event.TreeExpansionEvent evt) {//GEN-FIRST:event_visitTreeTreeExpanded

        if (((DefaultMutableTreeNode) evt.getPath().getLastPathComponent()).getUserObject() instanceof HealingSet) {
           //visitTreeValueChanged(null);
        }
    }//GEN-LAST:event_visitTreeTreeExpanded

    private void newVisitButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newVisitButtonActionPerformed

        try
        {
        if (dogsTable.getSelectedRowCount() == 0 || !(dogsTable.getValueAt(dogsTable.getSelectedRow(), 0) instanceof Dog))
            throw new FormException("Выберите cобаку и курс лечения");
        
            if(visitTree.getSelectionCount() == 0)
                throw new FormException("Выберите курс лечения которому должен принадлежать визит");
            HealingSet set = null;
            DefaultMutableTreeNode node;
            int sel[] = visitTree.getSelectionRows();
            for (int i = 0; i < sel.length; i++) {
                node = (DefaultMutableTreeNode) visitTree.getPathForRow(sel[i]).getLastPathComponent();
                if (node.getUserObject() instanceof HealingSet) {
                    set = (HealingSet) node.getUserObject();
                    node = null;
                    break;
                }
            }
            if (set == null) {
                throw new FormException("Выберите курс лечения которому должен принадлежать визит");
            }

            NewVisit nv = new NewVisit(frame, user,
                    (Dog) dogsTable.getValueAt(dogsTable.getSelectedRow(), 0), set, null);
            nv.setParentWindow(this);
            nv.setVisible(true);
           
        }catch(FormException e)
        {
            frame.FormException(this, e.getMessage());
        }
}//GEN-LAST:event_newVisitButtonActionPerformed

    private void newHealingActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newHealingActionPerformed
        if (dogsTable.getSelectedRowCount() != 0 && dogsTable.getValueAt(dogsTable.getSelectedRow(), 0) instanceof Dog ) {

            NewVisit nv = new NewVisit(frame, user,
                    (Dog) dogsTable.getValueAt(dogsTable.getSelectedRow(), 0), null, null);
            nv.setParentWindow(this);
            nv.setVisible(true);
        } else {
            frame.SQLException(new SQLException("Выберите животное"));
        }
}//GEN-LAST:event_newHealingActionPerformed

    private void changeVisitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_changeVisitActionPerformed
        if(activeVisit != null)
        {
                NewVisit nv = new NewVisit(frame, user,
                        (Dog) dogsTable.getValueAt(dogsTable.getSelectedRow(), 0),
                        activeVisit.getBelongsTo(), activeVisit);
                nv.setParentWindow(this);
                nv.setVisible(true);
        }else
        if (dogsTable.getValueAt(dogsTable.getSelectedRow(), 0) instanceof Dog && dogsTable.getSelectedRowCount() != 0 && visitTree.getSelectionCount() != 0) {
            HealingSet set = null;
            ItemList visit = null;
            DefaultMutableTreeNode node;
            int sel[] = visitTree.getSelectionRows();
            node = (DefaultMutableTreeNode) visitTree.getPathForRow(sel[0]).getLastPathComponent();
            if (node.getUserObject() instanceof HealingSet) {
                set = (HealingSet) node.getUserObject();
                node = null;
            } else if (node.getUserObject() instanceof ItemList) {
                visit = (ItemList) node.getUserObject();
                DefaultMutableTreeNode parent = (DefaultMutableTreeNode)node.getParent();
                set = (HealingSet)parent.getUserObject();
            }
            

            if (set == null && visit == null)
            {
                frame.SQLException(new SQLException("Выберите курс лечения или визит"));
            }
            if (visit != null) {
                NewVisit nv = new NewVisit(frame, user,
                        (Dog) dogsTable.getValueAt(dogsTable.getSelectedRow(), 0), visit.getBelongsTo(), visit);
                nv.setParentWindow(this);
                nv.setVisible(true);
            }

        } else {
            frame.SQLException(new SQLException("Выберите cобаку и курс лечения"));
        }
}//GEN-LAST:event_changeVisitActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        try {
            fastDogAdd fda = new fastDogAdd(frame, user,this);
            fda.setVisible(true);
        } catch (SQLException ex) {
            frame.FormException(this, ex.getMessage());
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    private void closeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_closeButtonActionPerformed
        this.dispose();
    }//GEN-LAST:event_closeButtonActionPerformed

    private void dogsTableKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_dogsTableKeyReleased
        if(evt.getKeyCode() == KeyEvent.VK_F2 || evt.getKeyCode() == KeyEvent.VK_RIGHT)
            visitTree.requestFocus();
        else
            dogsTableMousePressed(null);

    }//GEN-LAST:event_dogsTableKeyReleased

    private void visitDescrStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_visitDescrStateChanged
        if(visitDescr.getSelectedIndex() == 1)
        {
            
           // visitDescr.add("Фин. Отчет", fInfo.getContentPane());

        }
    }//GEN-LAST:event_visitDescrStateChanged

    private void visitTreeMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_visitTreeMouseReleased
        
        visitTreeValueChanged(null);
    }//GEN-LAST:event_visitTreeMouseReleased

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        if(oldVisits != null && oldVisits.isVisible())
        oldVisits.dispose();
    }//GEN-LAST:event_formWindowClosing

    public void resetValues(int id)
    {
        visitToSelect = id;
        dogsTableMousePressed(null);
    }

    public void setActiveVisit(ItemList il)
    {
        activeVisit = il;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton changeVisit;
    private javax.swing.JButton closeButton;
    private javax.swing.JTable dogsTable;
    private javax.swing.JButton jButton2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JLabel loadingLabel;
    private javax.swing.JButton newHealing;
    private javax.swing.JButton newVisitButton;
    private javax.swing.JButton selectAll;
    private javax.swing.JToggleButton showDetails;
    private javax.swing.JTextPane usersAddressLabel;
    private javax.swing.JLabel usersNameLabel;
    private javax.swing.JTabbedPane visitDescr;
    private javax.swing.JTree visitTree;
    private javax.swing.JLabel visitsHeader;
    // End of variables declaration//GEN-END:variables
}
